package com.zrrd.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.zrrd.reggie.bean.Employee;
import com.zrrd.reggie.bean.User;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.common.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class loginCheckFilter implements Filter {
    //路径匹配工具
    public static final AntPathMatcher PATH_MATCHER =new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //将请求对象进行类型转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //获取本次请求的uri获取，在request中
            String url = req.getRequestURI();
            log.info("当前地址==》"+url);
            String[] urls =new String[]{
                    "/employee/login",
                    "/employee/logout",
                    "/backend/**",
                    "/front/**",
                    "/user/sendMsg",
                    "/user/login"
            };
            //上面是不需要处理的请求
            //判断是不是不需要请求的路径
            if (isCheckUrl(urls,url)){
                chain.doFilter(req,res);
                return;
            }
            //判断id
            Long empId = (Long) req.getSession().getAttribute("emp");
            if (empId!=null) {
                ThreadLocalUtil.setCurrentId(empId);
                    chain.doFilter(req,res);
                    return;
            }
            //移动端登录
            //从user里面
            User user = (User) req.getSession().getAttribute("user");
            if (user!=null){
                ThreadLocalUtil.setCurrentId(user.getId());
                //放行
                chain.doFilter(req,res);
                return;
            }

        //告诉前端未登录
        res.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
    }
    private boolean isCheckUrl(String[] urls,String url){
        for (String s:urls){
            boolean match = PATH_MATCHER.match(s, url);
            if (match){
                return true;
            }
        }
        return false;
    }


}
